//
//  WebViewController.swift
//  shopAssistant
//
//  Created by 周文杰 on 2016/10/26.
//  Copyright © 2016年 com.weitaming. All rights reserved.
//

import UIKit
import Kingfisher

class WebViewController: UIViewController , UIWebViewDelegate {
    
    static let VCID = "WebViewController"

    var shareObj : ShareObject?

    var url : String?
    
    @IBOutlet weak var webView: UIWebView!
    
    @IBOutlet weak var toolbar: UIView!
    
//    init(url: String) {
//        super.init(nibName: nil, bundle: nil)
//        self.url = url
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        webView.backgroundColor = self.view.backgroundColor
//        webView.scrollView.contentInset = UIEdgeInsets(64, 0, 0, 0)

        if self.shareObj == nil {
            self.toolbar.isHidden = true
            webView.dataDetectorTypes = UIDataDetectorTypes.all
            webView.delegate = self
            webView.scalesPageToFit = true
        }else{
            webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 48, right: 0)
        }
        
        self.loadURL(self.url!)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - ***Public Method***
    func loadURL(_ urlString: String) -> Void {
        var url = URL(string: urlString)
        if url == nil {
            url = URL(string:urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        }
        
        webView.loadRequest(URLRequest(url: url!))
    }

    func loadFile(_ path: String) -> Void {

        let url = URL(fileURLWithPath: path)
        webView.loadRequest(URLRequest.init(url: url))
//        let htmlData = try? Data(contentsOf: url)
        //        webView.loadHTMLString(htmlStr, baseURL: nil)
//        webView.load(htmlData!, mimeType: "text/html", textEncodingName: "utf-8", baseURL: URL() )
    }
    
    func loadHTMLText(_ content: String) -> Void {
//        let htmlData = NSData(base64EncodedString: content, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
        
        webView.loadHTMLString(content, baseURL: nil)
//        webView.loadData(htmlData!, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: NSURL() )
    }
    
    func share2WX(_ scene: WXScene) {
        
        if !WXApi.isWXAppInstalled() {
            self.navigationController!.view.makeToast("请安装微信客户端")
//            return;
        }
        if let img = self.shareObj?.image {
            self.doShare2WX(img, scene:scene)
            return;
        }
        
        guard let url = URL(string:(shareObj?.imageUrl)!) else{
            let image = UIImage.init(named:"logo")
            self.doShare2WX(image!, scene:scene)
            return
        }

        KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            if error == nil {
                self.doShare2WX(image!, scene:scene)

            }else { //图片下载失败，默认图片
                //生成缩略图
                let image = UIImage.init(named:"logo")
                self.doShare2WX(image!, scene:scene)
            }
        }
        
        
    }
    
    func doShare2WX(_ image:UIImage ,scene: WXScene) {
        let ext = WXWebpageObject()
        ext.webpageUrl = self.shareObj?.url
        
        let message = WXMediaMessage()
        message.title = shareObj?.title
        message.description = nil
        message.mediaObject = ext
        message.mediaTagName = "MyPic"
        
        let req=SendMessageToWXReq()
        req.text=nil
        req.bText=false
        req.scene=Int32(scene.rawValue)
        
        let size = CGSize.init(width: 120, height: 120)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size ) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        message.thumbData=thumbImage!.jpegData(compressionQuality: 0.6)
        req.message=message
        WXApi.send(req)
    }
    
    @IBAction func onTapTimeline(_ sender: Any) {
        self.share2WX(WXSceneTimeline)
    }
    
    @IBAction func onTapWeibo(_ sender: Any) {
        if (!WeiboSDK.isWeiboAppInstalled()) {
            self.navigationController!.view.makeToast("请安装新浪微博客户端")
            return;
        }
            if let img = self.shareObj?.image {
                self.share2Weibo(img)
                return
            }
            
            guard  let url = URL(string:(shareObj?.imageUrl)!) else {
                let image = UIImage.init(named:"logo")
                self.share2Weibo(image!)
                return
            }
            
            KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
                if error == nil {
                    self.share2Weibo(image!)

                }else { //图片下载失败，默认图片
                    //生成缩略图
                    let image = UIImage.init(named:"logo")
                    self.share2Weibo(image!)
                }
            }
    }
    
    func share2Weibo(_ image:UIImage) {
        
        let webpageObject = WBWebpageObject()
        webpageObject.webpageUrl = self.shareObj?.url
        webpageObject.objectID = ""
        webpageObject.title = self.shareObj?.title
        
        let message = WBMessageObject()
        message.mediaObject = webpageObject
        //            if text != nil {
        //                message.text = text!
        //            }
        
        let sendMessageToWeiboRequest = WBSendMessageToWeiboRequest()
        sendMessageToWeiboRequest.message = message
        
        let size = CGSize.init(width: 100, height: 100)

        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        webpageObject.thumbnailData = thumbImage!.jpegData(compressionQuality: 0.6)
        WeiboSDK.send(sendMessageToWeiboRequest)
    }
    
    @IBAction func onTapWechatSession(_ sender: Any) {
        self.share2WX(WXSceneSession)
    }
    
    @IBAction func onTapQQ(_ sender: Any) {
        
        if !QQApiInterface.isQQInstalled() {
            self.navigationController!.view.makeToast("请安装手机QQ客户端")
            return;
        }
        
        let newsUrl = URL(string: (self.shareObj?.url)!)
        let title = self.shareObj?.title
        let description = ""
        var previewImageUrl = URL(string: "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png")
        if let url = URL(string: (self.shareObj?.imageUrl)!) {
            previewImageUrl = url
        }
        let newsObj = QQApiNewsObject(url: newsUrl, title: title, description: description,
                                      previewImageURL: previewImageUrl,
                                      targetContentType: QQApiURLTargetTypeNews)
        let req = SendMessageToQQReq(content: newsObj)
        QQApiInterface.send(req)
    }
    
    
    @IBAction func onTapQzone(_ sender: Any) {
        
        
        let newsUrl = URL(string: (self.shareObj?.url)!)
        let title = self.shareObj?.title
        let description = ""
        let previewImageUrl = URL(string: (self.shareObj?.imageUrl)!)
        let newsObj = QQApiNewsObject(url: newsUrl, title: title, description: description,
                                      previewImageURL: previewImageUrl,
                                      targetContentType: QQApiURLTargetTypeNews)
        let req = SendMessageToQQReq(content: newsObj)
        QQApiInterface.sendReq(toQZone: req)

    }
    
    @IBAction func onTapLove(_ sender: Any) {
    }
    
    public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool
    {
//        let url = request.url;
//        if url?.scheme == "tel" {
//            UIApplication.shared.openURL(url!)
//        }
        return true;
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "var element = document.createElement('meta');  element.name = \"viewport\";  element.content = \"width=device-width,initial-scale=1.0,minimum-scale=0.5,maximum-scale=3,user-scalable=1\"; var head = document.getElementsByTagName('head')[0]; head.appendChild(element);")
    }

}
